// 公共工具模块
const CommonUtil = {
    showLoading: function() {
        document.getElementById('loading-bg').style.display = 'block';
        document.getElementById('loading-spinner').style.display = 'block';
    },

    hideLoading: function() {
        document.getElementById('loading-bg').style.display = 'none';
        document.getElementById('loading-spinner').style.display = 'none';
    },

    handleError: function(error, customMessage = '') {
        console.error('Error:', error);
        UIModule.showError(customMessage || error.message || '操作失败，请重试');
    }
};

// 聊天功能模块
const ChatModule = {
    sendMessage: async function(initialMessage = null) {
        const input = document.getElementById('chatInput');
        const message = initialMessage || input.value.trim();
        
        if (!message) return;
        input.value = '';
        
        if (!initialMessage) {
            this.appendMessage('user', message);
        }
        
        // 创建消息容器
        const messagesDiv = document.getElementById('chatMessages');
        const messageContainer = document.createElement('div');
        messageContainer.className = 'message';

        // 创建思考过程容器（独立于消息容器）
        const thinkingContent = document.createElement('div');
        thinkingContent.className = 'thinking-content';
        messagesDiv.appendChild(thinkingContent);
        
        // 创建AI回答容器
        const assistantMessage = document.createElement('div');
        assistantMessage.className = 'assistant-message';
        const responseContent = document.createElement('div');
        responseContent.className = 'message-content';
        responseContent.innerHTML = '<div class="sender-label">DeepSeek：</div>';
        assistantMessage.appendChild(responseContent);
        messageContainer.appendChild(assistantMessage);
        
        messagesDiv.appendChild(messageContainer);
        
        try {
            const response = await fetch('/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message: message })
            });
            
            if (!response.ok) throw new Error('Network response was not ok');
            
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            
            let thinkingText = '';
            let responseText = '';
            let isThinking = false;
            
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;
                
                const chunk = decoder.decode(value);
                const lines = chunk.split('\n').filter(line => line.trim());
                
                for (const line of lines) {
                    try {
                        const data = JSON.parse(line);
                        if (data.content) {
                            if (data.content.includes('思考过程:')) {
                                isThinking = true;
                                continue;
                            } else if (data.content.includes('回答:')) {
                                isThinking = false;
                                continue;
                            }
                            
                            if (isThinking) {
                                thinkingText += data.content;
                                thinkingContent.textContent = thinkingText;
                                thinkingContent.style.opacity = '1';
                            } else {
                                responseText += data.content;
                                responseContent.innerHTML = `
                                    <div class="sender-label">DeepSeek：</div>
                                    ${responseText}
                                `;
                            }
                        }
                    } catch (error) {
                        console.error('Error parsing line:', error);
                    }
                }
                
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            }
        } catch (error) {
            console.error('Error:', error);
            responseContent.innerHTML = '<p class="error-message">发送消息失败，请稍后重试。</p>';
        }
    },

    appendMessage: function(role, content) {
        const messagesDiv = document.getElementById('chatMessages');
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${role}-message`;
        
        // 如果是AI助手的回答，创建空容器等待流式内容
        if (role === 'assistant') {
            messageDiv.innerHTML = `
                <div class="message-content">
                    <div class="sender-label">DeepSeek：</div>
                </div>
            `;
        } else {
            messageDiv.innerHTML = `
                <div class="message-content">
                    <div class="sender-label">${role === 'user' ? '用户：' : '系统：'}</div>
                    ${content}
                </div>
            `;
        }

        messagesDiv.appendChild(messageDiv);
        const clearDiv = document.createElement('div');
        clearDiv.style.clear = 'both';
        messagesDiv.appendChild(clearDiv);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
        
        return messageDiv;
    },

    appendTypingIndicator: function() {
        const messagesDiv = document.getElementById('chatMessages');
        const typingDiv = document.createElement('div');
        typingDiv.className = 'message assistant-message';
        
        typingDiv.innerHTML = `
            <div class="message-content">
                <div class="sender-label">DeepSeek：</div>
                <div class="typing-indicator">
                    <span></span><span></span><span></span>
                </div>
                <div>正在思考回答...</div>
            </div>
        `;
        
        messagesDiv.appendChild(typingDiv);
        const clearDiv = document.createElement('div');
        clearDiv.style.clear = 'both';
        messagesDiv.appendChild(clearDiv);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
        
        return typingDiv;
    },

    insertQuestion: function(element) {
        const chatInput = document.getElementById('chatInput');
        chatInput.value = element.textContent;
        chatInput.focus();
    }
};

// 图片识别模块
const ImageModule = {
    previewImage: function(input, previewId) {
        const preview = document.getElementById(previewId);
        const file = input.files[0];
        if (file) {
            if (!file.type.startsWith('image/')) {
                alert('请上传图片文件！');
                input.value = '';
                preview.src = '';
                return;
            }
            if (file.size > 5 * 1024 * 1024) {
                alert('图片大小不能超过 5MB！');
                input.value = '';
                preview.src = '';
                return;
            }
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.src = e.target.result;
                preview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }
    },

    handlePredict: async function(event) {
        event.preventDefault();
        const fileInput = document.getElementById('imageInput');
        const file = fileInput.files[0];
        
        if (!file) {
            alert('请选择一张图片');
            return;
        }
        
        const formData = new FormData();
        formData.append('file', file);
        
        try {
            document.getElementById('predictionResult').style.display = 'none';
            document.getElementById('classificationRules').style.display = 'none';
            document.getElementById('similarHistorySection').style.display = 'none';
            
            const response = await fetch('/predict', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            if (result.error) {
                UIModule.showError(result.error);
                return;
            }
            
            this.displayPredictionResult(result);
            HistoryModule.loadHistory();
        } catch (error) {
            console.error('Error:', error);
            UIModule.showError('预测出错，请重试');
        }
    },

    displayPredictionResult: function(result) {
        document.getElementById('predictionResult').style.display = 'block';
        document.getElementById('classificationRules').style.display = 'block';
        
        document.getElementById('mainClass').textContent = result.main_class;
        document.getElementById('detailedClass').textContent = result.detailed_class;
        document.getElementById('confidence').textContent = result.confidence.toFixed(2);
        document.getElementById('categoryDefinition').textContent = result.definition;
        document.getElementById('disposalRules').textContent = result.rules;

        const similarHistorySection = document.getElementById('similarHistorySection');
        const similarHistoryImages = document.getElementById('similarHistoryImages');
        similarHistoryImages.innerHTML = '';

        if (result.similar_history && result.similar_history.length > 0) {
            // 只显示相似度大于65%的图片
            const filteredSimilarHistory = result.similar_history.filter(img => img.similarity > 65.0);
            
            if (filteredSimilarHistory.length > 0) {
                similarHistorySection.style.display = 'block';
                similarHistoryImages.innerHTML = filteredSimilarHistory.slice(0, 4).map(img => {
                    // 格式化时间戳显示
                    let timeStr = '未知时间';
                    if (img.timestamp) {
                        try {
                            const date = new Date(img.timestamp);
                            timeStr = date.toLocaleString(); // 格式化为本地日期时间格式
                        } catch(e) {
                            console.error('时间格式化错误:', e);
                            timeStr = img.timestamp; // 如果格式化失败，则显示原时间戳
                        }
                    }
                    
                    return `
                        <div class="col-md-3 col-sm-6 mb-3">
                            <div class="card h-100 border-light">
                                <img src="${img.image_url}" alt="相似图片" class="card-img-top" style="height: 150px; object-fit: cover;">
                                <div class="card-body p-2">
                                    <p class="card-text small mb-1">
                                        <strong>主类别：</strong>${img.main_class}<br>
                                        <strong>详细类别：</strong>${img.detailed_class}<br>
                                        <strong>相似度：</strong>${img.similarity.toFixed(2)}%<br>
                                        <strong>时间：</strong>${timeStr}
                                    </p>
                                </div>
                            </div>
                        </div>
                    `;
                }).join('');
            } else {
                similarHistorySection.style.display = 'block';
                similarHistoryImages.innerHTML = '<div class="col-12 text-center"><p class="alert alert-info">您的历史记录中的图片数量过少，请多使用图片识别功能</p></div>';
            }
        } else {
            similarHistorySection.style.display = 'block';
            similarHistoryImages.innerHTML = '<div class="col-12 text-center"><p class="alert alert-info">您的历史记录中的图片数量过少，请多使用图片识别功能</p></div>';
        }
    }
};

// 相似图片搜索模块
const SimilarSearchModule = {
    init: function() {
        document.getElementById('similarSearchForm').addEventListener('submit', this.handleSearch.bind(this));
    },

    showLoading: function() {
        document.getElementById('loadingOverlay').style.display = 'flex';
    },

    hideLoading: function() {
        document.getElementById('loadingOverlay').style.display = 'none';
    },

    handleSearch: async function(event) {
        event.preventDefault();
        const formData = new FormData(event.target);
        const file = formData.get('file');
        
        if (!file) {
            UIModule.showError('请选择图片');
            return;
        }

        this.showLoading();
        
        try {
            const response = await fetch('/search_similar', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            if (!data.success) {
                throw new Error(data.error || '搜索失败');
            }
            
            this.displayResults(data);
        } catch (error) {
            CommonUtil.handleError(error, '搜索相似图片失败');
        } finally {
            this.hideLoading();
        }
    },

    displayResults: function(data) {
        const resultDiv = document.getElementById('similarUploadResult');
        const searchResultsDiv = document.getElementById('similarSearchResults');
        const resultsContainer = document.getElementById('similarImagesContainer');
        
        // 显示上传图片的分类结果
        resultDiv.innerHTML = `
            <div class="alert alert-info mb-0">
                <h6 class="mb-2">图片识别结果：</h6>
                <p class="mb-1"><strong>主类别：</strong>${data.main_class || '未知'}</p>
                <p class="mb-1"><strong>详细类别：</strong>${data.detailed_class || '未知'}</p>
                <p class="mb-0"><strong>置信度：</strong>${data.confidence ? data.confidence.toFixed(2) : 0}%</p>
            </div>
        `;
        resultDiv.style.display = 'block';
        
        // 显示相似图片结果
        if (data.similar_images && data.similar_images.length > 0) {
            console.log("接收到的相似图片数据:", data.similar_images);
            
            resultsContainer.innerHTML = data.similar_images
                .slice(0, 4)
                .map((img, index) => {
                    // 确定使用哪个URL属性，优先使用image_url
                    const imgUrl = img.image_url || img.path || '';
                    console.log(`图片${index + 1}的URL:`, imgUrl);
                    
                    return `
                        <div class="col-md-6 mb-3">
                            <div class="card h-100">
                                <div class="card-body text-center">
                                    <img src="${imgUrl}" alt="相似图片" class="img-fluid mb-2" 
                                         style="max-height: 150px; object-fit: contain;"
                                         onerror="this.onerror=null; this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22200%22 height=%22200%22><rect width=%22200%22 height=%22200%22 fill=%22%23eee%22/><text x=%22100%22 y=%22100%22 fill=%22%23aaa%22 text-anchor=%22middle%22 dominant-baseline=%22middle%22>加载失败(${img.path ? img.path.substring(0, 20) + '...' : '无路径'})</text></svg>';">
                                    <div class="small">
                                        <p class="mb-1">
                                            <strong>主类别：</strong>${img.main_class}<br>
                                            <strong>详细类别：</strong>${img.detailed_class}<br>
                                            <strong>相似度：</strong>${img.similarity ? img.similarity.toFixed(2) : 0}%
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                }).join('');
            searchResultsDiv.style.display = 'block';
        } else {
            resultsContainer.innerHTML = '<div class="alert alert-info col-12">未找到相似图片</div>';
            searchResultsDiv.style.display = 'block';
        }
    }
};

// 搜索模块
const SearchModule = {
    performTextSearch: function(query) {
        fetch('/text_search', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ query: query })
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                // 处理后端返回的错误信息
                const searchResults = document.getElementById('searchResults');
                const countDiv = document.createElement('div');
                countDiv.className = 'alert alert-warning mb-4';
                countDiv.innerHTML = data.error;
                searchResults.innerHTML = '';
                searchResults.appendChild(countDiv);
                return;
            }
            this.displaySearchResults(data.results);
        })
        .catch(error => {
            // 处理前端错误
            const searchResults = document.getElementById('searchResults');
            const countDiv = document.createElement('div');
            countDiv.className = 'alert alert-warning mb-4';
            countDiv.innerHTML = '没有找到相关图片，请换一种描述方式';
            searchResults.innerHTML = '';
            searchResults.appendChild(countDiv);
        });
    },

    displaySearchResults: function(results) {
        const searchResults = document.getElementById('searchResults');
        if (results.length === 0) {
            searchResults.innerHTML = '<div class="alert alert-warning">没有找到相关图片</div>';
            return;
        }

        const countDiv = document.createElement('div');
        countDiv.className = 'alert alert-success mb-4';
        countDiv.innerHTML = `找到 ${results.length} 张相关图片`;
        
        const gridContainer = document.createElement('div');
        gridContainer.className = 'image-grid-container';

        // 限制最多显示16张图片
        const displayResults = results.slice(0, 16);
        
        // 创建4x4网格布局
        gridContainer.innerHTML = `
            <div class="image-grid">
                ${displayResults.map(img => {
                    const pathParts = decodeURIComponent(img.path).split('/');
                    const categoryPart = pathParts[pathParts.length - 2];
                    const [mainClass, detailedClass] = categoryPart.split('_');
                    
                    return `
                        <div class="grid-item">
                            <div class="grid-card">
                                <div class="img-wrapper">
                                    <img src="${img.path}" alt="搜索结果"
                                         onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22200%22 height=%22200%22><rect width=%22200%22 height=%22200%22 fill=%22%23eee%22/><text x=%22100%22 y=%22100%22 fill=%22%23aaa%22 text-anchor=%22middle%22 dominant-baseline=%22middle%22>加载失败</text></svg>';">
                                </div>
                                <div class="category-label">
                                    <strong>${mainClass}-${detailedClass}</strong>
                                </div>
                            </div>
                        </div>
                    `;
                }).join('')}
            </div>
        `;
        
        searchResults.innerHTML = '';
        searchResults.appendChild(countDiv);
        searchResults.appendChild(gridContainer);
    }
};

// 历史记录模块
const HistoryModule = {
    loadHistory: async function() {
        try {
            const response = await fetch('/history');
            const data = await response.json();
            
            const historyContainer = document.getElementById('historyContainer');
            if (!data || data.length === 0) {
                historyContainer.innerHTML = '<div class="col-12"><p class="text-center">暂无历史记录</p></div>';
                return;
            }
            
            historyContainer.innerHTML = data.map(item => `
                <div class="col-md-3 col-sm-6 mb-3">
                    <div class="card h-100">
                        <button class="delete-btn" data-filename="${item.history_file}" onclick="HistoryModule.deleteHistory('${item.history_file}')">
                            <i class="fas fa-trash"></i>
                        </button>
                        <img src="${item.image_url}" class="card-img-top" alt="历史图片" 
                             style="height: 150px; object-fit: cover;"
                             onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22150%22 height=%22150%22 fill=%22%23eee%22/><text x=%2275%22 y=%2275%22 fill=%22%23aaa%22 text-anchor=%22middle%22 dominant-baseline=%22middle%22>加载失败</text></svg>';">
                        <div class="card-body">
                            <h6 class="card-title mb-1">预测结果</h6>
                            <p class="card-text small mb-1">主类别: ${item.main_class}</p>
                            <p class="card-text small mb-1">详细类别: ${item.detailed_class}</p>
                            <p class="card-text small mb-1">置信度: ${item.confidence.toFixed(2)}%</p>
                            <p class="card-text small text-muted">时间: ${new Date(item.timestamp).toLocaleString()}</p>
                        </div>
                    </div>
                </div>
            `).join('');
        } catch (error) {
            console.error('加载历史记录失败:', error);
            UIModule.showError('加载历史记录失败');
        }
    },

    deleteHistory: async function(filename) {
        if (!filename || filename === 'undefined' || filename === 'null') {
            UIModule.showError('无效的文件名');
            return;
        }
        
        if (!confirm('确定要删除这条历史记录吗？')) return;
        
        try {
            const response = await fetch('/delete_history/' + encodeURIComponent(filename), {
                method: 'DELETE'
            });
            
            if (response.ok) {
                this.loadHistory();
                if (document.getElementById('similar-search').classList.contains('active')) {
                    const similarSearchForm = document.getElementById('similarSearchForm');
                    if (similarSearchForm) {
                        const formData = new FormData(similarSearchForm);
                        if (formData.get('image')) {
                            const searchResponse = await fetch('/search_similar', {
                                method: 'POST',
                                body: formData
                            });
                            const data = await searchResponse.json();
                            SimilarSearchModule.displaySimilarResults(data);
                        }
                    }
                }
            } else {
                const text = await response.text();
                UIModule.showError('删除失败: ' + text);
            }
        } catch (error) {
            console.error('删除失败:', error);
            UIModule.showError('删除失败，请重试');
        }
    }
};

// UI交互模块
const UIModule = {
    showError: function(message) {
        alert(message);
    },

    initializeTabs: function() {
        const buttons = document.querySelectorAll('.function-button');
        buttons.forEach(button => {
            button.addEventListener('click', function() {
                buttons.forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                const targetId = this.getAttribute('data-target');
                UIModule.switchTab(targetId);
                
                if (targetId === '#history') {
                    HistoryModule.loadHistory();
                }
            });
        });
        
        if (buttons.length > 0) {
            buttons[0].click();
        }
    },

    switchTab: function(tabId) {
        const tabPanes = document.querySelectorAll('.tab-pane');
        tabPanes.forEach(pane => {
            pane.classList.remove('active', 'show');
        });
        
        const targetPane = document.querySelector(tabId);
        if (targetPane) {
            targetPane.classList.add('active');
            setTimeout(() => {
                targetPane.classList.add('show');
            }, 150);
        }
    },

    showSuccess: function(message) {
        // 可以在未来实现更好的成功提示UI
        console.log('Success:', message);
    }
};

// 知识问答功能
let quizData = null;
let selectedAnswers = {};

function displayQuizQuestions(questions) {
    const container = document.getElementById('quizContainer');
    container.innerHTML = '<h4>垃圾分类知识问答</h4>';
    
    quizData = questions; // 保存题目数据
    selectedAnswers = {}; // 重置选择的答案
    
    questions.forEach((question, index) => {
        const questionCard = document.createElement('div');
        questionCard.className = 'question-card';
        questionCard.id = `question-${index}`;
        
        let optionsHtml = '';
        if (question.type === 'choice') {
            // 选择题
            question.options.forEach((option, optionIndex) => {
                const optionLabel = String.fromCharCode(65 + optionIndex);
                optionsHtml += `
                    <button class="option-btn" data-question="${index}" data-answer="${optionLabel}">
                        ${optionLabel}. ${option}
                    </button>
                `;
            });
        } else {
            // 判断题
            optionsHtml = `
                <button class="option-btn" data-question="${index}" data-answer="对">对</button>
                <button class="option-btn" data-question="${index}" data-answer="错">错</button>
            `;
        }
        
        questionCard.innerHTML = `
            <div class="question-text">${index + 1}. ${question.question}</div>
            <div class="options-container">${optionsHtml}</div>
            <div id="feedback-${index}" class="result-feedback"></div>
        `;
        
        container.appendChild(questionCard);
    });
    
    // 添加提交按钮
    const submitButton = document.createElement('button');
    submitButton.className = 'btn btn-primary mt-4';
    submitButton.textContent = '提交答案';
    submitButton.onclick = submitQuiz;
    container.appendChild(submitButton);
    
    // 添加结果显示区域
    const resultDiv = document.createElement('div');
    resultDiv.id = 'quizResult';
    container.appendChild(resultDiv);
    
    // 为所有选项按钮添加点击事件
    document.querySelectorAll('.option-btn').forEach(button => {
        button.addEventListener('click', function() {
            const questionIndex = this.dataset.question;
            const answer = this.dataset.answer;
            
            // 移除同一题目其他选项的选中状态
            document.querySelectorAll(`.option-btn[data-question="${questionIndex}"]`).forEach(btn => {
                btn.classList.remove('selected');
            });
            
            // 添加当前选项的选中状态
            this.classList.add('selected');
            
            // 保存答案
            selectedAnswers[questionIndex] = answer;
        });
    });
}

function submitQuiz() {
    if (!quizData) return;
    
    let score = 0;
    let totalQuestions = quizData.length;
    
    // 检查是否所有题目都已作答
    if (Object.keys(selectedAnswers).length < totalQuestions) {
        UIModule.showError('请回答所有题目后再提交');
        return;
    }
    
    // 计算得分并显示正确答案
    quizData.forEach((question, index) => {
        const questionCard = document.getElementById(`question-${index}`);
        const feedbackDiv = document.getElementById(`feedback-${index}`);
        const userAnswer = selectedAnswers[index];
        const correctAnswer = question.type === 'choice' ? 
            String.fromCharCode(65 + question.options.indexOf(question.answer)) : // 选择题答案转换为ABCD
            question.answer; // 判断题答案为"对"或"错"
        
        // 显示用户答案和正确答案
        let answerText = '';
        if (question.type === 'choice') {
            const userAnswerText = question.options[userAnswer.charCodeAt(0) - 65];
            const correctAnswerText = question.answer;
            answerText = `
                <div class="answer-detail">
                    <div>你的答案：${userAnswer}. ${userAnswerText}</div>
                    <div>正确答案：${correctAnswer}. ${correctAnswerText}</div>
                </div>
            `;
        } else {
            answerText = `
                <div class="answer-detail">
                    <div>你的答案：${userAnswer}</div>
                    <div>正确答案：${correctAnswer}</div>
                </div>
            `;
        }
        
        if (userAnswer === correctAnswer) {
            score++;
            feedbackDiv.innerHTML = `
                <span class="correct">回答正确</span>
                ${answerText}
            `;
        } else {
            feedbackDiv.innerHTML = `
                <span class="incorrect">回答错误</span>
                ${answerText}
            `;
        }
        
        // 禁用选项按钮
        const optionButtons = questionCard.querySelectorAll('.option-btn');
        optionButtons.forEach(btn => {
            btn.disabled = true;
            if (btn.textContent.trim().startsWith(correctAnswer)) {
                btn.classList.add('correct-answer');
            }
        });
    });
    
    // 根据分数显示不同的评语
    let title = '';
    if ((score / totalQuestions * 100) === 100) {
        title = '环保大使';
    } else if ((score / totalQuestions * 100) >= 90) {
        title = '环保卫士';
    } else if ((score / totalQuestions * 100) >= 80) {
        title = '分类小王子';
    } else if ((score / totalQuestions * 100) >= 70) {
        title = '分类小能手';
    } else if ((score / totalQuestions * 100) >= 60) {
        title = '分类新手';
    } else {
        title = '继续努力';
    }
    
    // 显示结果弹窗
    showResultModal(score, totalQuestions, title);
    
    // 禁用提交按钮
    const submitButton = document.querySelector('#quizContainer .btn-primary');
    submitButton.disabled = true;
}

// 获取问答题目
document.getElementById('startQuiz').addEventListener('click', function() {
    fetch('/get_questions')
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                UIModule.showError(data.error);
                return;
            }
            displayQuizQuestions(data.questions);
            document.getElementById('startQuiz').style.display = 'none';
            document.getElementById('quizContainer').style.display = 'block';
        })
        .catch(error => {
            console.error('获取题目出错:', error);
            UIModule.showError('获取题目出错: ' + error);
        });
});

function showResultModal(score, totalQuestions, title) {
    const modal = document.createElement('div');
    modal.className = 'modal-backdrop';
    
    const scorePercentage = Math.round((score / totalQuestions) * 100);
    
    modal.innerHTML = `
        <div class="result-modal">
            <h3>测试结果</h3>
            <div class="score">${scorePercentage}分</div>
            <div class="title">${title}</div>
            <div class="stats">
                <p>总题数：${totalQuestions}</p>
                <p>正确题数：${score}</p>
            </div>
            <button class="close-btn" onclick="closeResultModal(this)">关闭</button>
            <button class="restart-btn" onclick="restartQuiz()">重新答题</button>
        </div>
    `;
    
    document.body.appendChild(modal);
}

function restartQuiz() {
    // 关闭结果弹窗
    const modal = document.querySelector('.modal-backdrop');
    if (modal) {
        modal.remove();
    }
    
    // 重置答题状态
    selectedAnswers = {};
    
    // 重新获取题目
    fetch('/get_questions')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 随机打乱题目顺序
                const shuffledQuestions = shuffleArray(data.questions);
                // 只取前10题
                const selectedQuestions = shuffledQuestions.slice(0, 10);
                displayQuizQuestions(selectedQuestions);
                quizData = selectedQuestions;
            } else {
                UIModule.showError('获取题目失败：' + data.error);
            }
        })
        .catch(error => {
            UIModule.showError('获取题目出错: ' + error);
        });
}

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

function closeResultModal(button) {
    const modal = button.closest('.modal-backdrop');
    modal.style.opacity = '0';
    setTimeout(() => {
        modal.remove();
    }, 300);
}

// 图片理解模块
const ImageUnderstandingModule = {
    currentImage: null,
    
    init() {
        // 选择文件时预览图片
        $('#understandingImageInput').on('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            // 显示文件名
            $('#understandingFileNameDisplay').text(file.name);
            
            // 预览图片
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#understandingImagePreview')
                    .attr('src', e.target.result)
                    .css('display', 'block');
                ImageUnderstandingModule.currentImage = file;
            };
            reader.readAsDataURL(file);
        });
        
        // 处理表单提交
        $('#imageUnderstandingForm').on('submit', function(e) {
            e.preventDefault();
            ImageUnderstandingModule.uploadImage();
        });

        // 添加回车键发送问题的功能
        $('#followUpQuestion').on('keypress', function(e) {
            if (e.key === 'Enter') {
                ImageUnderstandingModule.sendFollowUpQuestion();
            }
        });
    },
    
    uploadImage() {
        if (!this.currentImage) {
            alert('请先选择图片');
            return;
        }
        
        const formData = new FormData();
        formData.append('file', this.currentImage);
        
        // 隐藏之前的结果
        $('#understandingResult').hide();
        $('#followUpSection').hide();
        $('#firstAnswer').html('');
        $('#followUpAnswer').html('');
        const submitBtn = $('#imageUnderstandingForm button[type="submit"]');
        submitBtn.prop('disabled', true);
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> 分析中...');
        
        $.ajax({
            url: '/image_understanding',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $('#firstAnswer').html(response.answer);
                    $('#understandingResult').show();
                    // 显示后续问答区域
                    $('#followUpSection').show();
                    // 清空并聚焦到后续问题输入框
                    $('#followUpQuestion').val('').focus();
                } else {
                    alert(response.error || '分析失败，请重试');
                }
            },
            error: function() {
                alert('服务器错误，请重试');
            },
            complete: function() {
                submitBtn.prop('disabled', false);
                submitBtn.html('<i class="fas fa-brain"></i> 开始分析');
            }
        });
    },
    
    sendFollowUpQuestion() {
        const question = $('#followUpQuestion').val().trim();
        if (!question) {
            alert('请输入问题');
            return;
        }
        
        // 显示加载状态
        const submitBtn = $('#followUpSection button');
        submitBtn.prop('disabled', true);
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> 分析中...');
        $('#followUpAnswer').html('');
        
        $.ajax({
            url: '/image_understanding_follow_up',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ message: question }),
            success: function(response) {
                if (response.success) {
                    $('#followUpAnswer').html(response.answer);
                    // 清空输入框
                    $('#followUpQuestion').val('');
                } else {
                    alert(response.error || '获取回答失败，请重试');
                }
            },
            error: function() {
                alert('服务器错误，请重试');
            },
            complete: function() {
                submitBtn.prop('disabled', false);
                submitBtn.html('<i class="fas fa-paper-plane"></i> 发送问题');
            }
        });
    }
};

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化各个模块
    UIModule.initializeTabs();
    SimilarSearchModule.init();
    ImageUnderstandingModule.init();
    
    // 加载历史记录
    HistoryModule.loadHistory();
    
    // 注册事件监听器
    document.getElementById('chatInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') ChatModule.sendMessage();
    });
    
    document.getElementById('uploadForm').addEventListener('submit', ImageModule.handlePredict.bind(ImageModule));
    
    // 更新文件输入框的事件监听
    document.getElementById('imageInput').addEventListener('change', function(e) {
        ImageModule.previewImage(this, 'imagePreview');
        // 显示文件名
        const fileName = e.target.files[0] ? e.target.files[0].name : '未选择文件';
        document.getElementById('fileNameDisplay').textContent = fileName;
    });

    document.getElementById('similarImageUpload').addEventListener('change', function(e) {
        // 显示文件名
        const fileName = e.target.files[0] ? e.target.files[0].name : '未选择文件';
        document.getElementById('similarFileNameDisplay').textContent = fileName;
    });
    
    // 加载搜索提示词
    fetch('/get_search_suggestions')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.suggestions) {
                const suggestionTags = document.getElementById('suggestionTags');
                suggestionTags.innerHTML = data.suggestions
                    .map(suggestion => `
                        <span class="suggestion-tag m-1" onclick="SearchModule.performTextSearch('${suggestion}')">
                            ${suggestion}
                        </span>
                    `).join('');
            }
        })
        .catch(error => CommonUtil.handleError(error, '加载搜索提示词失败'));
});
